package grimbo.goodwinfooty;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

import org.supercsv.io.CsvListReader;
import org.supercsv.io.ICsvListReader;
import org.supercsv.prefs.CsvPreference;

public class CSV2List {
    int skipFirstLines = 0;
    String lastLineValue = null;

    public CSV2List() {
    }

    public int getSkipFirstLines() {
        return skipFirstLines;
    }

    public void setSkipFirstLines(int skipFirstLines) {
        if (skipFirstLines < 0) {
            throw new IllegalArgumentException("skipFirstLines must be > 0");
        }
        this.skipFirstLines = skipFirstLines;
    }

    public String getLastLineValue() {
        return lastLineValue;
    }

    public void setLastLineValue(String lastLineValue) {
        this.lastLineValue = lastLineValue;
    }

    public List convertCSV2List(Reader r) throws IOException {
        List lines = readLines(r);
        return lines;
    }

    public List convertCSV2List(byte[] bytes) throws IOException {
        InputStreamReader r = new InputStreamReader(new ByteArrayInputStream(bytes));

        return convertCSV2List(r);

    }

    private List readLines(Reader r) throws IOException {
        List lines = new ArrayList();

        BufferedReader br = (r instanceof BufferedReader) ? (BufferedReader) r : new BufferedReader(r);

        ICsvListReader lr = new CsvListReader(br, CsvPreference.EXCEL_PREFERENCE);

        try {
            int skipFirstLines = this.skipFirstLines;
            for (List line = lr.read(); null != line; line = lr.read()) {
                if (skipFirstLines > 0) {
                    skipFirstLines--;
                    continue;
                }
                boolean isLastLine = (null != lastLineValue) && (line.size() > 0) && (lastLineValue.equals(line.get(0)));
                if (isLastLine) {
                    break;
                }
                String[] strs = new String[line.size()];
                line.toArray(strs);
                lines.add(strs);
            }
        } finally {
            lr.close();
        }
        return lines;
    }

}
